package repository.impl;

import Util.JDBCtool;
import entity.Book;
import entity.BookCase;
import repository.BookRepository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookRepositoryImpl implements BookRepository {
    @Override
    public List<Book> findAll(int index,int limit) throws SQLException {
        Connection connection= JDBCtool.getConnection();
        String sql="select * from book ,bookcase where book.bookcase=bookcase.id limit ?,?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setInt(1,index);
        preparedStatement.setInt(2,limit);
        ResultSet resultSet=preparedStatement.executeQuery();
        List<Book> list=new ArrayList<>();
        while(resultSet.next()){
            /*BookCase bookCase=new BookCase(resultSet.getInt(7),resultSet.getString(8));
            Book book=new Book(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),
                    resultSet.getString(4),resultSet.getDouble(5),bookCase);
            list.add(book);*/
            list.add(new Book(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),
                    resultSet.getString(4),resultSet.getInt(5),resultSet.getDouble(6),new BookCase(resultSet.getInt(8),resultSet.getString(9))));
            }
        JDBCtool.release(connection,preparedStatement,resultSet);
        return list;
    }

    @Override
    public int count() throws SQLException {
        Connection connection=JDBCtool.getConnection();
        String sql="select count(*) from book ,bookcase where book.bookcase=bookcase.id";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        ResultSet resultSet=preparedStatement.executeQuery();
        int count=0;
        while(resultSet.next()){
            count=resultSet.getInt(1);
        }
        JDBCtool.release(connection,preparedStatement,resultSet);
        return count;
    }
}
